/**
 * Created by dukes on 2015/12/7.
 */
module  game{
    export class BroadcastHandler {
        public static CHAT_WORLD:string = "Chat.world";
        public static CHAT_SYSTEM:string = "Chat.system";
        public static CHAT_PERSONAL:string = "Chat.personal";
        public static PROP_REMOVE:string = "UserProp.remove";//道具过期移除推送
        public static DECORATE_REMOVE:string = "UserOrnament.remove";//装扮过期移除推送
        public static BUFF_REMOVE:string = "TimerBuff.remove";//buff过期移除推送
        public static BUFF_ADD:string = "TimerBuff.add";//buff过期移除推送
        public static MAIL_ADD:string = "UserMail.add";//收到邮件推送
        public static MAIL_REMOVE:string = "UserMail.remove";//收到邮件删除
        public static MISSION_LIST:string = "UserMission.list";//任务、成就、解锁变更推送
        public static PET_UPDATE:string = "Pet.hair";//宠物自身毛变更推送[被掠夺推送]
        public static HAIR_UPDATE:string = "Pet.petHair";//宠物毛变更推送[被掠夺推送]
        public static PET_WAR_LIST:string = "PetWar.list";//宠物战斗数据推送
        public static ACTIVITY_CHARGE: string = "Activity.charge";//宠物毛变更推送[被掠夺推送]
        public static ACTIVITY_CAT:string = "Activity.fortuneCat";//宠物战斗数据推送
        public static ACTIVITY_VSCORE:string = "Activity.vipScore";//Vip积分活动数据推送
        public static USER_UPDATE:string = "User.update";//用户数据变更数据推送
        public static USER_EXT_UPDATE:string = "UserExtendInfo.update";//用户扩展信息更新
        public static GUILD_APPLY:string = "Family.apply";//家族申请新增推送
        public static GUILD_APPROVE:string = "Family.approve";//用户家族申请通过推送
        public static GUILD_KICKOUT:string = "Family.kickout";//族长踢出族员推送
        public static GUILD_DISMISS:string = "Family.disband";//族长解散家族推送
        public static GUILD_REFUSE:string = "Family.reject";//族长拒绝加入申请

        public static GUILD_APPROVE_M:string = "Family.member.approve";//族长同意加入申请
        public static GUILD_KICK_M:string = "Family.member.kick";//族长踢出族员
        public static GUILD_QUIT_M:string = "Family.member.quit";//成员退出家族
        //public static GUILD_MACHINE_REAP:string = "Family.machines.reap";//机器可收取
        //public static GUILD_MACHINE_UPGRADE:string = "Family.machines.upgrade";//机器升级完毕
        //public static GUILD_MACHINE_REFUEL:string = "Family.machines.refuel";//加油机器
        //public static GUILD_MACHINE_MAINTANCE:string = "Family.machines.maintain";//保养机器
        public static GUILD_WAREHOUSE_BOX:string = "Family.warehouse.boxes";//仓库箱子更新

        public static GUILD_MESSAGE_ADD:string = "Family.message.add";//留言板消息新增
        public static GUILD_MESSAGE_CLEAN:string = "Family.message.clean";//留言板消息 清空
        public static GUILD_MY_MACHINE:string = "Family.machine";//机器数据刷新
        public static GUILD_DATA:string = "Family.data";//家族数据刷新

        public static ACTIVITY_LIMIT_HAIR:string = "Activity.timeLimitedHair";//限时购毛数据推送
        public static ACTIVITY_LIMIT_DEC: string = "Activity.timeLimitedOrnament";//限时购毛数据推送


        public static Connected: boolean = false;

        public static RECONNECTED_MARK:egret.Bitmap;
        private static timer:number = -1;
        public static updateConnectionStat(isConnected,code) {
            BroadcastHandler.Connected = isConnected;
            if (!BroadcastHandler.Connected) {
                if( Model.GuideStarted){
                    GuideController.getInstance().cleanStep();
                }
                if( code == 4001 && Model.me.platform == PlatformEnum.QQBROWSER){
                    RemindPanel.getInstance().showContent("账号在其他设备登录，需要重新登录。",null,BroadcastHandler.onLogout,null,false);
                    return;
                }
                if (code != 4001 && code != 1006) {
                    if( BroadcastHandler.timer == -1){
                        BroadcastHandler.timer = setTimeout(BroadcastHandler.reconnect,30000);
                    }
                   BroadcastHandler.reconnect();
                }
                if (!BroadcastHandler.RECONNECTED_MARK) {
                    BroadcastHandler.RECONNECTED_MARK = new egret.Bitmap(RES.getRes("reconnect"));
                    BroadcastHandler.RECONNECTED_MARK.x = GameConst.Stage.stageWidth - BroadcastHandler.RECONNECTED_MARK.texture.textureWidth >> 1;
                    BroadcastHandler.RECONNECTED_MARK.y = 110;
                    BroadcastHandler.RECONNECTED_MARK.touchEnabled = true;
                    BroadcastHandler.RECONNECTED_MARK.addEventListener(egret.TouchEvent.TOUCH_TAP, BroadcastHandler.reconnect, null)
                }
                GameConst.Stage.addChild(BroadcastHandler.RECONNECTED_MARK);
            }else{
                if( BroadcastHandler.timer != -1){
                    clearInterval(BroadcastHandler.timer);
                    BroadcastHandler.timer = -1;
                }

                if (BroadcastHandler.RECONNECTED_MARK && BroadcastHandler.RECONNECTED_MARK.parent) {
                    GameConst.Stage.removeChild(BroadcastHandler.RECONNECTED_MARK);
                }
            }
        }
        public static onLogout(){
            window["logout"]();
        }

        private static reconnect(){
            window["__startWS"]();
        }

        public static handle(data){
            Model.SYSTIME = data.date;
            if( data.code!= 0 ){
                egret.log(data.si,data.message);
                return;
            }
            switch (data.si){
                case BroadcastHandler.PROP_REMOVE:
                    BroadcastHandler.handlerPropRemove(data.payload);
                    break;
                case BroadcastHandler.DECORATE_REMOVE:
                    BroadcastHandler.handlerDecRemove(data.payload);
                    break;
                case BroadcastHandler.BUFF_REMOVE:
                    BroadcastHandler.handlerBuffRemove(data.payload);
                    break;
                case BroadcastHandler.BUFF_ADD:
                    BroadcastHandler.handlerBuffAdd(data.payload);
                    break;
                case BroadcastHandler.MAIL_ADD:
                    BroadcastHandler.handlerMailAdd(data.payload);
                    RedPointMgr.getInstance().update(RedPointMgr.MAIL_ICON,true);
                    break;
                case BroadcastHandler.MAIL_REMOVE:
                    BroadcastHandler.handlerMailRemove(data.payload);
                    break;
                case BroadcastHandler.MISSION_LIST:
                    BroadcastHandler.handlerMissionList(data.payload);
                    break;
                case BroadcastHandler.PET_UPDATE:
                    BroadcastHandler.handlerPetUpdate(data.payload);
                    break;
                case BroadcastHandler.HAIR_UPDATE:
                    BroadcastHandler.handlerHairUpdate(data.payload);
                    break;
                case BroadcastHandler.CHAT_WORLD:
                    ChatMgr.getInstance().addWorldChatData(data.payload);
                    break;
                case BroadcastHandler.CHAT_SYSTEM:
                    ChatMgr.getInstance().addSystemChatData(data.payload);
                    break;
                case BroadcastHandler.CHAT_PERSONAL:
                    ChatMgr.getInstance().addChatInfo(data.payload);
                    RedPointMgr.getInstance().update(RedPointMgr.CHAT_ICON,true);
                    RedPointMgr.getInstance().update(RedPointMgr.CHAT_TAB,true);
                    break;
                case BroadcastHandler.PET_WAR_LIST:
                    Model.petAttributes = data.payload;
                    if( PlayBar.getInstance().parent)
                        PlayBar.getInstance().updateDecorateRelated();
                    if( DateScene.getInstance().parent)
                        DateScene.getInstance().updateWarRelated();
                    break;
                case BroadcastHandler.ACTIVITY_CHARGE:
                    ActivityMgr.getInstance().chargeInfo = data.payload;
                    MainScene.getInstance().updateRechargeRelated();
                    break;
                case BroadcastHandler.ACTIVITY_CAT:
                    ActivityMgr.getInstance().moneyCatInfo = data.payload;
                    var curConfig:MoneyCatAcitivityConfig = ActivityMgr.getInstance().getCurMoneyCatConfig();
                    RedPointMgr.getInstance().update(RedPointMgr.MONEY_CAT_ICON,curConfig!=null && curConfig.diamond <=  ActivityMgr.getInstance().moneyCatInfo.totalCharge );
                    break;
                case BroadcastHandler.ACTIVITY_VSCORE:
                    ActivityMgr.getInstance().vipInfo = data.payload;
                    var status = data.payload.dailyLoginStatus == 1 || data.payload.successionLoginStatus == 1 || data.payload.pillageWinStatus == 1;
                    RedPointMgr.getInstance().update(RedPointMgr.VIP_MISSION,status);
                    if( VipPanel.getInstance().parent)
                        VipPanel.getInstance().updateScoreRelated();
                    break;
                case BroadcastHandler.USER_UPDATE:
                    Model.me.initFromData(data.payload);
                    DiamondElement.getInstance().updateDisplay();
                    if( VipPanel.getInstance().parent)
                        VipPanel.getInstance().updateScoreRelated();
                    break;
                case BroadcastHandler.USER_EXT_UPDATE:
                    Model.userExt = data.payload;
                    break;
                
                case BroadcastHandler.ACTIVITY_LIMIT_HAIR:
                    BroadcastHandler.onLimitHair(data.payload);
                    break;
                case BroadcastHandler.ACTIVITY_LIMIT_DEC:
                    BroadcastHandler.onLimitDec(data.payload);
                    break;
                default:
                    egret.log("Unkonwn service:",data.si);
                    break;
            }
        }
        public static onLimitDec(data){
            if (LimitBuyDecorate.getInstance().parent)
                LimitBuyDecorate.getInstance().onInfoBack(data);
        }
        public static onLimitHair(data){
            MainScene.getInstance().onInfoBack(data);
        }
       

        public static onPetWarList(list:any[]){
            var war;
            var len =  Model.petAttributes.length;
            for(var j = 0; j < list.length; j++){
                war = list[j];
                var found;
                var iwar;
                for(var i = 0; i < len; i++){
                    iwar = Model.petAttributes[i];
                    if( iwar.petId == war.petId){
                        Model.petAttributes[i] = war;
                        found = true;
                        break;
                    }
                }
                if( !found){
                    Model.petAttributes.push(war);
                    len++;
                }
            }

            if( PlayBar.getInstance().parent)
                PlayBar.getInstance().updateDecorateRelated();
        }

        public static handlerDecRemove(list:any[]){
            var len = list.length;
            var goodsId;
            for( var i=0; i < len; i++){
                goodsId = list[i];
                if( Model.HasFreeDec(goodsId))
                    var dec = Model.DeleteFreeDec(goodsId);
                else
                    dec =  Model.DeleteDec(goodsId);
            }
            if( DecorateScene.getInstance().parent)
                DecorateScene.getInstance().onDressBack();
            else if( MainScene.getInstance().parent)
                MainScene.getInstance().updateItems();
        }

        public static handlerPropRemove(list:any[]){
            //Model.setPropCnt
            var len = list.length;
            var goodsId;
            for( var i=0; i < len; i++) {
                goodsId = list[i];
                if( goodsId != 0){
                    Model.setPropCnt(goodsId,0);
                }
            }
        }

        public static handlerBuffRemove(data:any){
            var data;
            var buffid:number;
            var len;
            var pid;
            for(var petId in data){
                pid = parseInt(petId);
                if( pid != 0){
                    len = data[petId].length;
                    for(var i = 0; i < len; i++){
                        buffid = data[petId][i];
                        if( buffid != 0)
                            BuffMgr.getInstance().deleteBuff(pid,buffid);
                    }
                }
            }
        }

        public static handlerBuffAdd(data:any){
            BuffMgr.getInstance().addBuff(data);
            if( data.buffId == BuffMgr.SHIELD_BUFF){
                if( MainScene.getInstance().parent != null) {
                    MainScene.getInstance().updateShield();
                }
            }
        }
        public static handlerMailRemove(data:number[]){
            if( !Model.curMails) return;
            var mailId;
            while(data.length) {
                mailId = data.pop();
                Model.DeleteMailById(mailId);
            }
            if( MailScene.getInstance().parent)
                MailScene.getInstance().updateMails()
        }
        public static handlerMailAdd(data:any){
            if( Model.curMails){
                var mailInfo:MailInfo = new MailInfo(data);
                Model.curMails.push(mailInfo);
                Model.mailMap[mailInfo.id] = true;
            }
            //var mailInfo:MailInfo = new MailInfo(data);
            //Model.curMails.push(mailInfo);
            RedPointMgr.getInstance().update(RedPointMgr.MAIL_ICON,true);
            if( MailScene.getInstance().parent != null){
                MailScene.getInstance().updateMails();
            }
        }
        public static handlerPetUpdate(data:any){
            PetMgr.getInstance().updatePet(data);//todo 需要验证
        }
        public static handlerHairUpdate(data:any){
            if( data.type == Model.GOOD_TYPE_CAT){
                Model.me.catHair = data.hair;
            }else if( data.type == Model.GOOD_TYPE_DOG){
                Model.me.dogHair = data.hair;
            }
            DiamondElement.getInstance().updateDisplay();
        }
        public static handlerMissionList(list:any[]){
            var hasFinishedAcvhieve:boolean = false;
            var hasFinishedMission:boolean = false;
            var len = list.length;
            var info;
            var mission:MissionInfo;

            for(var idx = 0 ; idx < len; idx++){
                info = list[idx];
                if( info.type == Model.TYPE_MISSION){
                    mission = Model.missionModels[info.missionId];
                    if(  Model.curMissions.indexOf(info.missionId) == -1){//info.status != 2 &&
                        Model.curMissions.push(mission.id);
                    }
                }else if( info.type == Model.TYPE_ACHIVEMENT ){
                    mission = Model.achieveModels[info.missionId];
                    if( info.status != 2 && Model.curAchievements.indexOf(info.missionId) == -1){
                        if( info.status != 1)
                            Model.curAchievements.push(mission.id);
                        else
                            Model.curAchievements.unshift(mission.id);
                    }else if( info.status == 2){
                        var index = Model.curAchievements.indexOf(info.missionId);
                        Model.curAchievements.splice(index,1);
                    }else if( info.status == 1){
                        var indx = Model.curAchievements.indexOf(info.missionId);
                        if( indx != -1)
                            Model.curAchievements.splice(indx,1);
                        Model.curAchievements.unshift(mission.id);
                    }
                }else if( info.type == Model.TYPE_UNLOCK){
                    mission = Model.unlockModels[info.missionId];
                }else{//104类型的任务是服务端用的
                    continue;
                }
                mission.status = info.status;
                mission.currStep = info.currStep || 0;
                if( mission.status == 1){
                    if( mission.type == Model.TYPE_ACHIVEMENT)
                        hasFinishedAcvhieve = true;
                    else
                        hasFinishedMission = true;
                }
            }

            if( hasFinishedAcvhieve ){
                RedPointMgr.getInstance().update(RedPointMgr.ACTIVITY_ICON,true);
                RedPointMgr.getInstance().update(RedPointMgr.ACHIEVE,true);
            }

            if( hasFinishedMission )
                RedPointMgr.getInstance().update(RedPointMgr.TRAVE_ICON,true);

            if( ActivityPanel.getInstance().parent != null && mission && mission.type == Model.TYPE_ACHIVEMENT){
                ActivityPanel.getInstance().updateMissions();
            }

            if(  TravelPanel.getInstance().parent){
                TravelPanel.getInstance().updateList();
            }
        }
    }
}